/*
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.
*/

class Solution {
public:
    string countAndSay(int n) {
        string cur("1");
        for (int i = 2; i <= n; i++) {
            cur = getNext(cur);
        }
        return cur;
    }
private: 
    string getNext(const string &str) {
        string next("");
        for (int i = 0; i < str.length(); ) {
            int start = i, count = 0;
            while (str[i] == str[start]) {
                count++; i++;
            }
            // insert into current string
            next += to_string(count);
            next += str[start];
        }
        return next;
    }
};

#if 0
class Solution {
public:
    string countAndSay(int n) {
        string curstr(""); 
        if (!n) return curstr;
        curstr.assign("1"); // n=1
        for (int i=2; i<=n; i++) {
            string nextstr("");
            nextStr(curstr, nextstr);
            curstr = nextstr; // copy to next
        }
        return curstr;
    }
private:
    void nextStr(const string &curstr, string &nextstr) {
        int i = 0, count=0;
        do {
            char cstart = curstr[i];
            while (i < curstr.length() && curstr[i] == cstart) {i++; count++;}
            nextstr += ('0'+count);
            nextstr += cstart;
            count = 0;
        } while (i < curstr.length());
    }
};
#endif
